//
//  ViewController.m
//  ggsdkdemooc
//
//  Created by lenbo lan on 2021/9/25.
//

#import "ViewController.h"

#import <BUAdSDK/BUAdSDK.h>

#import <AFNetworking.h>

#import <jhsdk/Reachability.h>
#import <jhsdk/AppManager.h>
#import <jhsdk/AppReport.h>

@interface ViewController ()<BURewardedVideoAdDelegate>
{
    NSString *curAdId; //广告ID
    NSUInteger curAdIndex;
    NSUInteger curAdClick; // 去重 当前点击的广告索引
    
    NSUInteger curAdOpenTime; // 当前广告打开时间
    NSUInteger curAdStartLoadTime; // 当前广告开始加载时间
    NSUInteger curAdDataLoadedTime; // 当前广告数据加载完成时间
    NSUInteger curAdVideoLoadedTime; // 当前广告视频加载完成时间
    NSUInteger curAdShowTime; // 广告展示时间
    NSUInteger curAdClickTime; // 广告点击时间
    NSUInteger curAdJumpTime; // 用户点击跳过时间
    
}

@property (nonatomic) Reachability *internetReachability;

@property (nonatomic, strong) BURewardedVideoAd *rewardedVideo;

@property (nonatomic, copy) NSString *createdView;

@property (nonatomic, strong) UIButton *btnRewardAd;
@property (nonatomic, strong) UIButton *btnUpload;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    curAdIndex = 0;
    curAdClick = 0;
    
//    是否打开日志输出，默认否
    [AppManager setLogEnable:YES];
    
    _createdView = @"";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    self.internetReachability = [Reachability reachabilityForInternetConnection];
    [self.internetReachability startNotifier];
    [self updateInterfaceWithReachability:self.internetReachability];
    
    [self configUI];
}

- (void)configUI {
    self.view.backgroundColor = UIColor.whiteColor;
    
    CGFloat s_wid = [UIScreen mainScreen].bounds.size.width;
    
    _btnRewardAd = [self createBtn:@"打卡签到" frame:CGRectMake(s_wid/2-60, 120, 120, 40)];
    [_btnRewardAd addTarget:self action:@selector(onTapRewardAd) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnRewardAd];
    
    _btnUpload = [self createBtn:@"上传凭证" frame:CGRectMake(s_wid/2-60, 240, 120, 40)];
    [_btnUpload addTarget:self action:@selector(onTapUpload) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnUpload];
}

-(UIButton *)createBtn:(NSString *)title frame:(CGRect)frame {
    UIButton *btn = [[UIButton alloc]initWithFrame:frame];
    btn.layer.borderWidth = 1;
    btn.layer.cornerRadius = 8;
    btn.layer.borderColor = UIColor.grayColor.CGColor;
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:UIColor.grayColor forState:UIControlStateNormal];
    return btn;
}

-(void)onTapRewardAd {
    [AppManager popup:self naviId:1];
}

-(void)onTapUpload {
    // 打开推广窗口
    [AppManager popup:self naviId:2];
}

-(void)requestRewardedVideoAd {
    _rewardedVideo = nil;
    
    NSString *rewardAdId = @"946584884";
    
    [BUAdSDKManager setAppID:@"5209222"];
    
    // 激励视频 AdType 为 4
    curAdId = [AppReport createAdId:4];
    curAdIndex += 1;
    
    BURewardedVideoModel *rewardModel = [[BURewardedVideoModel alloc]init];
    
    // 广告开始加载的时间
    curAdStartLoadTime = [self currentTimeInt];
    
    _rewardedVideo = [[BURewardedVideoAd alloc]initWithSlotID:rewardAdId rewardedVideoModel:rewardModel];
    _rewardedVideo.delegate = self;
    
    // 上报开始加载广告
    [[AppReport shareInstance]rAdStart:AdPlatformBU
                                adType:AdTypeReward
                                  adId:curAdId];
    
    [_rewardedVideo loadAdData];
}

/// 获取当前时间戳
- (NSUInteger)currentTimeInt{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970]; //*1000;// *1000 是精确到毫秒，不乘就是精确到秒
    return (NSUInteger)time;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}

#pragma mark - Detection network

- (void) reachabilityChanged:(NSNotification *)note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    [self updateInterfaceWithReachability:curReach];
}

- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
    NSLog(@"===== updateInterfaceWithReachability =====");
    if (reachability == self.internetReachability) {
        NetworkStatus netStatus = [reachability currentReachabilityStatus];
        switch (netStatus) {
            case NotReachable:
                break;
            case ReachableViaWWAN:
                [self requestAdParams];
                break;
            case ReachableViaWiFi:
                [self requestAdParams];
                break;
            case kReachableVia2G:
                [self requestAdParams];
                break;
            case kReachableVia3G:
                [self requestAdParams];
                break;
            case kReachableVia4G:
                [self requestAdParams];
                break;
        }
    }
}

#pragma mark - Request parameters

-(void) requestAdParams {
    if (_createdView.length > 0) {
        return;
    }
    _createdView = @"1";
    
    NSDictionary *dic = @{@"bundleid":@"com.yky.sdktest", @"version":@"1"};
    
//    NSString *bundle = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
//    NSString *ver = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
//    NSNumber *ret = @([ver integerValue]);
//    NSDictionary *dic = @{@"bunddleid":bundle, @"version":ret};
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/json", @"text/javascript",@"text/html", nil ,nil];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];//加上这句话，要不一直报415请求接收错误
    // manager.requestSerializer.timeoutInterval = 5;
    // manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:@"https://app.niuit.cn/index.php/cms/wxapp.index/ad" parameters:dic headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *listArray = responseObject[@"data"];
        [AppManager setupParams:listArray];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark - BURewardedVideoAdDelegate

-(void)rewardedVideoAdDidLoad:(BURewardedVideoAd *)rewardedVideoAd {
    // 广告 数据 加载完成时间
    curAdDataLoadedTime = [self currentTimeInt];
}

-(void)rewardedVideoAdVideoDidLoad:(BURewardedVideoAd *)rewardedVideoAd {
    // 广告 视频 加载完成时间
    curAdVideoLoadedTime = [self currentTimeInt];
    // 上报视频加载完成
    [[AppReport shareInstance]rAdLoaded:AdPlatformBU
                                 adType:AdTypeReward
                                   adId:curAdId
                             loadedTime:curAdVideoLoadedTime];
    
    [rewardedVideoAd showAdFromRootViewController:self];
}

-(void)rewardedVideoAdDidVisible:(BURewardedVideoAd *)rewardedVideoAd {
    [[AppReport shareInstance]rAdShow:AdPlatformBU
                               adType:AdTypeReward
                                 adId:curAdId
                           loadedTime:curAdVideoLoadedTime];
    // 广告展示时间
    curAdShowTime = [self currentTimeInt];
}

-(void)rewardedVideoAdDidClose:(BURewardedVideoAd *)rewardedVideoAd {
    
    // 上报关闭广告
    [[AppReport shareInstance]rAdClose:AdPlatformBU
                                adType:AdTypeReward
                                  adId:curAdId
                              openTime:curAdOpenTime
                         startLoadTime:curAdStartLoadTime
                        dataLoadedTime:curAdVideoLoadedTime
                       videoLoadedTime:curAdVideoLoadedTime
                              showTime:curAdShowTime
                             clickTime:curAdClickTime
                              jumpTime:curAdJumpTime];
    
    [self resetTimeRecords];
}

-(void)resetTimeRecords {
    curAdId = @"";
    curAdOpenTime = 0;
    curAdStartLoadTime = 0;
    curAdDataLoadedTime = 0;
    curAdVideoLoadedTime = 0;
    curAdShowTime = 0;
    curAdClickTime = 0;
    curAdJumpTime = 0;
}

-(void)rewardedVideoAdDidClick:(BURewardedVideoAd *)rewardedVideoAd {
    int isRepeat = 1;
    if (curAdIndex != curAdClick) {
        curAdClick = curAdIndex;
        isRepeat = 0;
        curAdClickTime = [self currentTimeInt];
    }
    
    // 上报点击信息
    [[AppReport shareInstance]rAdClick:AdPlatformBU
                                adType:AdTypeReward
                                  adId:curAdId
                              showTime:curAdShowTime
                              isRepeat:isRepeat];
}

-(void)rewardedVideoAdDidClickSkip:(BURewardedVideoAd *)rewardedVideoAd {
    curAdJumpTime = [self currentTimeInt];
}

-(void)rewardedVideoAd:(BURewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *)error {
    NSString *msg = [NSString stringWithFormat:@"广告加载失败|%@", error.localizedDescription];
    // 上报错误信息
    [[AppReport shareInstance]rAdError:AdPlatformBU
                                adType:AdTypeReward
                                   err:msg
                                  adId:curAdId];
}

@end
